package net.easyjava.third.sms.huyi;

import net.easyjava.third.sms.huyi.result.SendResult;
import net.easyjava.tools.http.HttpTools;
import net.easyjava.tools.lang.StringTools;
import net.easyjava.tools.security.md5.Md5Tools;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wenxiaoning on 16/6/20.
 */
public class HuyiClient {
    private static Logger logger = LoggerFactory.getLogger(HuyiClient.class);


    /**
     *
     * @param account
     * @param password
     * @param mobile
     * @param content
     * @return
     * @throws IOException
     * @throws DocumentException
     * @throws HuyiException
     */
    public static SendResult send(String account,String password,String mobile,String content) throws IOException, DocumentException, NoSuchAlgorithmException {
        if(StringTools.isEmpty(account) || StringTools.isEmpty(password)
                || StringTools.isEmpty(mobile)|| StringTools.isEmpty(content)){
            throw new HuyiException("account , password , mobile , content all can't be empty");
        }

        String pwd = Md5Tools.md5(password);
        Map<String, String> params = new HashMap<String, String>();
        params.put("account", account);
        params.put("password", pwd);
        params.put("mobile", mobile);
        params.put("content", content);
        String str = null;
        int code = -1;
        boolean flag = true;
        str = HttpTools.post(HuyiConstants.URL_SEND, params);
        Document doc = DocumentHelper.parseText(str);
        Element root = doc.getRootElement();
        code = Integer.valueOf(root.elementText("code"));

        String msg = root.elementText("msg");
        String smsid = root.elementText("smsid");
        SendResult sendResult = new SendResult(smsid,code,msg);
        return sendResult;
    }


    public static void main(String[] args) {
        try {
            HuyiClient.send("cf_modengtk", "1234567", "18311233541", "亲爱的用户，感谢您对草莓音乐节的支持。因为露营区场地有限，为了给大家提供更好服务，我们需要再次核实您的露营需求。如果您确认露营，请您回复XY；如果不露营，请您回复BXY，您的露营资格也将被取消并分配给更需要露营的朋友。请您在收到此短信24小时内回复。再次感谢您的理解与支持。");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
